//
// Created by pengy on 2024/8/9.
//

#include "RadarFileTest.h"
#include "log/log.h"

#include <QFile>
#include <QTextStream>

RadarFileTest::RadarFileTest(QThread *parent) {
  LOGD("");
}

RadarFileTest::~RadarFileTest() {
  LOGD("");
}

int RadarFileTest::Start(const QString &filepath) {
  ReadRadarData(filepath);

  return 0;
}

void HexStrToBin(char data[], const QString &hexstr) {
  // 确保字符串长度是偶数
  QString padhex = hexstr;
  if (padhex.length() % 2 != 0) {
    padhex.prepend('0');
  }

  // 每两个字符组成一个字节
  for (int i = 0, j = 0; i < padhex.length(); i += 2, j++) {
    QString byte_s = padhex.mid(i, 2);
    bool is_ok;
    char byte = byte_s.toUInt(&is_ok, 16);
    if (is_ok) {
      data[j] = byte;
    }
  }
}

int RadarFileTest::ReadRadarData(const QString &filepath) {
  QFile file(filepath);

// 打开文件
  if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
    LOGE("open file %s failed.", filepath.toStdString().c_str());
    return -1;
  }

  int i = 0;
  QTextStream in(&file);
  while (!in.atEnd()) {
    QString line = in.readLine();

    // 使用逗号分割行
    // 2040,674,221,5A0C00A202DD003D211A005F
    QStringList fields = line.split(',');
    if (fields.size() >= 4) {
      if (fields[3].trimmed().indexOf("Data") != -1) {
        continue;
      }
      if ((i++) % 5 != 0) {  // 1/5插入
        continue;
      }

      LidarData item;
      item.pts = i;
      item.amp = fields[2].trimmed().toInt();
      item.dist = fields[1].trimmed().toInt();

      raw_data_.push_back(item);
    }
  }

  file.close();  // 关闭文件
  return 0;
}

void RadarFileTest::ProcRadarData() {

}
